const query = require('../config/connection');
//获取订单列表
async function getOrderListService (ctx, params) {
  const start = (params.pageNo - 1) * params.pageSize;
  // let sql = 'select * from orderinfo limit ' + start + ',' + params.pageSize;
  let sql = `SELECT petgoods.GoodsImage,orderinfo.* FROM orderinfo LEFT JOIN petgoods ON orderinfo.GoodsNo = petgoods.GoodsNo limit ${start},${params.pageSize}`;

  try {
    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": data
    }
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    }
  }
};
//获取小程序用户订单列表
async function getWXOrderListService (ctx, params) {
  const start = (params.pageNo - 1) * params.pageSize;
  // let sql = 'select * from orderinfo limit ' + start + ',' + params.pageSize;
  let sql = `SELECT petgoods.GoodsImage,orderinfo.* FROM orderinfo LEFT JOIN petgoods ON orderinfo.GoodsNo = petgoods.GoodsNo where UserId='${params.userId}' order by orderinfo.CreateDate desc limit ${start},${params.pageSize}`;

  try {
    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": data
    }
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    }
  }
};
//发货
async function sendGoodsService (ctx, params) {
  let sql = `update orderinfo set OrderStatus=1 where id=${params.id}`;
  try {
    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": "1"
    }
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    }
  }
};
//提交订单
async function submitOrderService (ctx, params) {
  let param = [];
  let key = [];
  for (let item in params) {
    let value = "'" + params[item] + "'"
    param.push(value)
    key.push(item)
  }
  let sql = `insert into orderinfo (${key.join(",")}) values(${param.join(",")})`;
  try {
    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": "1"
    }
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    }
  }
};
module.exports = {
  getOrderListService,
  getWXOrderListService,
  sendGoodsService,
  submitOrderService
}